package com.recipedb.sprint.security;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Component
public class JwtFilter extends OncePerRequestFilter {

    private final JwtUserDetailsService jwtUserDetailsService;

    public JwtFilter(JwtUserDetailsService jwtUserDetailsService) {
        this.jwtUserDetailsService = jwtUserDetailsService;
    }

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) {
        String path = request.getRequestURI();
        return path.equals("/api/users/login") || path.equals("/api/users/register");
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain)
            throws ServletException, IOException {

        System.out.println("\n=== JwtFilter 调试开始 ===");
        System.out.println("请求路径: " + request.getRequestURI());

        String header = request.getHeader("Authorization");
        System.out.println("请求头 Authorization: " + header);

        String username = null;

        if (header != null && header.startsWith("Bearer ")) {
            String token = header.substring(7);
            System.out.println("解析到的 Token: " + token);

            try {
                username = JwtUtil.validateToken(token);
                System.out.println("解析出的用户名: " + username);
            } catch (Exception e) {
                System.out.println("Token 验证异常: " + e.getMessage());
            }
        } else {
            System.out.println("请求头缺失或格式错误");
        }

        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            // ✅ 从数据库或内存中加载用户信息
            UserDetails userDetails = jwtUserDetailsService.loadUserByUsername(username);

            // ✅ 创建认证对象
            UsernamePasswordAuthenticationToken authentication =
                    new UsernamePasswordAuthenticationToken(
                            userDetails, null, userDetails.getAuthorities());

            authentication.setDetails(
                    new WebAuthenticationDetailsSource().buildDetails(request));

            // ✅ 把认证信息放进 SecurityContext
            SecurityContextHolder.getContext().setAuthentication(authentication);

            System.out.println("✅ 已设置认证用户到 SecurityContext: " + username);
        } else if (username == null) {
            System.out.println("⚠️ 未能从 Token 获取用户名，可能 token 无效或过期");
        }

        chain.doFilter(request, response);
        System.out.println("=== JwtFilter 调试结束 ===\n");
    }
}

